﻿Option Explicit On
Option Strict On

Imports System.Windows.Controls.Primitives

Public Class Dialog
    Private _grid As Grid
    Private _canvas As Canvas
    Private _popup As Popup

    Public Sub Show(ByVal ctl As Control, ByVal container As Panel, Optional ByVal dlgStyle As DialogStyle = DialogStyle.ModalDimmed)
        AddHandler Application.Current.Host.Content.Resized, AddressOf OnPluginSizeChanged
        _popup = New Popup()
        _grid = New Grid()
        _popup.Child = _grid
        If (dlgStyle <> DialogStyle.NonModal) Then
            _canvas = New Canvas()
            AddHandler _canvas.MouseLeftButtonDown, AddressOf OnClickOutSide
            If (dlgStyle = DialogStyle.Modal) Then
                _canvas.Background = New SolidColorBrush(Colors.Transparent)
            ElseIf (dlgStyle = DialogStyle.ModalDimmed) Then
                _canvas.Background = New SolidColorBrush(Color.FromArgb(32, 128, 128, 128))
            End If
            _grid.Children.Add(_canvas)
        End If
        _grid.Children.Add(ctl)
        container.Children.Add(_popup)
        UpdateSize()
        _popup.IsOpen = True
        ctl.Tag = Me
    End Sub

    Public Sub Close()
        If _popup IsNot Nothing Then
            _popup.IsOpen = False
            RemoveHandler Application.Current.Host.Content.Resized, AddressOf OnPluginSizeChanged
            _grid.Children.Clear()
            _grid = Nothing
            _canvas = Nothing
            CType(_popup.Parent, Panel).Children.Remove(_popup)
            _popup = Nothing
        End If
    End Sub

    Public Overridable Sub OnClickOutSide(ByVal sender As Object, ByVal e As EventArgs)
        'nothing to do - prevents clicks outside of modal dialog
    End Sub

    Private Sub OnPluginSizeChanged(ByVal sender As Object, ByVal e As EventArgs)
        UpdateSize()
    End Sub

    Private Sub UpdateSize()
        _grid.Width = Application.Current.Host.Content.ActualWidth
        _grid.Height = Application.Current.Host.Content.ActualHeight
        If _canvas IsNot Nothing Then
            _canvas.Width = _grid.Width
            _canvas.Height = _grid.Height
        End If
    End Sub

End Class

Public Enum DialogStyle
    NonModal
    Modal
    ModalDimmed
End Enum

